package com.uzai.console.service.fd.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.dto.goods.TextConvertGoodsDto;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.BeanMapUtil;
import com.uzai.console.common.utils.RandomUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.fd.fdsendjob.FdSendJobDto;
import com.uzai.console.dto.fd.fdturnlink.FdTurnlinkDto;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.fdSendJob.FdSendJobIdFeignDto;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.feign.turnlink.TbPartnerurlAnalysisDto;
import com.uzai.console.dto.pyq.pyqmaterial.TurnlinkDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsFdGroupSendMsg;
import com.uzai.console.enums.FdGoodsParaEnum;
import com.uzai.console.jsonvo.fd.fdtemplate.FdTemplateData;
import com.uzai.console.jsonvo.fd.fdtuo.FdTuoData;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdSendJobSyncService;
import com.uzai.console.service.feign.ClientApiService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.feign.dto.ConvertGoodsDto;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.FdSendMsgProducerService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.feign.turnlink.TbPartnerurlAnalysisVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 社群发单-发单任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdSendJobSyncServiceImpl implements FdSendJobSyncService {

    Logger logger = LoggerFactory.getLogger(FdSendJobSyncServiceImpl.class);

    @Autowired
    private FdDevicePlanGroupTuoMapper fdDevicePlanGroupTuoMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private FdSendJobMapper fdSendJobMapper;
    @Autowired
    private FdSendMsgProducerService fdSendMsgProducerService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private FdGoodsParaMapper fdGoodsParaMapper;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private ClientApiService clientApiService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /**
     * 创建发单任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param fdDevicePlanGroupList
     * @return null
     */
    //@Async("taskExecutor")
    @Override
    public void addFdSendJobTaskSync(FdSendJobDto fdSendJobDto, FdDevicePlan fdDevicePlan, List<FdDevicePlanGroup> fdDevicePlanGroupList, List<FdSendJob> fdSendJobList_sub){
        //查询所有发送内容
        List<FdTemplateData> fdTemplateDataList = fdSendJobDto.getFdTemplateDataList();
        //群与群之间的发送时间间隔
        int groupSendGap = Tools.getInteger(fdDevicePlan.getGroupSendGap());
        //逐群发送：一个任务中同一个内容每个群都发送完成之后，在发送下一个内容
        if(Tools.getInteger(fdDevicePlan.getSendRule()).intValue() == 0) {
            //先循环该商品，然后在循环子任务
            for (int i = 0; i < fdTemplateDataList.size(); i++) {
                //得到商品
                FdTemplateData fdTemplateData = fdTemplateDataList.get(i);
                //得到此商品的间隔时间
                int fdTemplate_gap = Tools.getInteger(fdTemplateData.getGap());
                //判断该商品为否为托
                if(Tools.getInteger(fdTemplateData.getMsgType()).intValue() != -1) {//不是托，则一个商品发送一次
                    //循环子任务（群），每个群发送该商品
                    for (int j = 0; j < fdSendJobList_sub.size(); j++) {
                        //取出子任务
                        FdSendJob fdSendJob = fdSendJobList_sub.get(j);
                        //取出群
                        FdDevicePlanGroup fdDevicePlanGroup = fdDevicePlanGroupList.get(j);
                        //取出该子任务的消息列表
                        List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob.getEsFdGroupSendMsgList();
                        //取出该子任务的最后发送时间间隔
                        int sendMsgDelay = fdSendJob.getSendMsgDelay();
                        if(i == 0){ //第一次循环，间隔时间为群与群之间的消息间隔 * 群数
                            sendMsgDelay = j * groupSendGap;
                        }else{//取出该任务的最后时间间隔+商品间隔时间
                            sendMsgDelay = sendMsgDelay + fdTemplate_gap;
                        }
                        //修改新的最后发送时间间隔
                        fdSendJob.setSendMsgDelay(sendMsgDelay);
                        //封装消息
                        EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                        esFdGroupSendMsg.setId(IdWorker.getIdStr());
                        //临时封装最后一条不是托信息的id
                        fdSendJob.setLastNoTuoMsgId(esFdGroupSendMsg.getId());
                        esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                        esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                        esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                        esFdGroupSendMsg.setDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                        if(device == null){
                            continue;
                        }
                        esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                        esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                        esFdGroupSendMsg.setMsgType(fdTemplateData.getMsgType());
                        esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                        esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                        esFdGroupSendMsg.setDelay(sendMsgDelay);
                        esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                        esFdGroupSendMsg.setRetry(0);
                        esFdGroupSendMsg.setVersion(0L);
                        esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                        esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                        //判断下个消息是否为托。
                        if( i+1 < fdTemplateDataList.size()){
                            FdTemplateData fdTemplateData_next = fdTemplateDataList.get(i+1);
                            if(fdTemplateData_next != null){
                                if(Tools.getInteger(fdTemplateData_next.getMsgType()).intValue() == -1) {//是托
                                    esFdGroupSendMsg.setNextIsTuo(1); //设置这个消息下一个消息是托
                                }
                            }
                        }
                        HashMap<String, String> msgHash = new HashMap<>();
                        if(fdTemplateData.getMsgType().intValue() == 0){ //文本消息
                            String content = fdTemplateData.getContent();
                            //替换商品变量
                            String content_new = contentTurnlink(content, fdDevicePlanGroup, fdDevicePlan, device);
                            msgHash.put("content", content_new);
                        }else if(fdTemplateData.getMsgType().intValue() == 1){
                            msgHash.put("imgUrl", fdTemplateData.getImgUrl());
                            msgHash.put("imgType", String.valueOf(fdTemplateData.getImgType()));
                        }else if(fdTemplateData.getMsgType().intValue() == 3){
                            msgHash.put("videoUrl", fdTemplateData.getVideoUrl());
                        }else if(fdTemplateData.getMsgType().intValue() == 5){
                            msgHash.put("cardTitle", fdTemplateData.getCardTitle());
                            msgHash.put("cardDes", fdTemplateData.getCardDes());
                            msgHash.put("cardImg", fdTemplateData.getCardImg());
                            msgHash.put("cardUrl", fdTemplateData.getCardUrl());
                        }else if(fdTemplateData.getMsgType().intValue() == 6){
                            msgHash.put("miniProAppId", fdTemplateData.getMiniProAppId());
                            msgHash.put("miniProTitle", fdTemplateData.getMiniProTitle());
                            msgHash.put("miniProDesc", fdTemplateData.getMiniProDesc());
                            msgHash.put("miniProUrl", fdTemplateData.getMiniProUrl());
                            msgHash.put("miniImgPwdStr", fdTemplateData.getMiniImgPwdStr());
                            msgHash.put("miniImgStr", fdTemplateData.getMiniImgStr());
                            msgHash.put("miniImgUrl", fdTemplateData.getMiniImgUrl());
                            msgHash.put("miniProGhId", fdTemplateData.getMiniProGhId());
                            msgHash.put("miniProName", fdTemplateData.getMiniProName());
                        }
                        esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                        //添加到子任务中的临时发送消息列表中
                        esFdGroupSendMsgList.add(esFdGroupSendMsg);
                    }
                }else{ //是托，则需要计算托的次数
                    //临时存放托词语的列表
                    List<String> tuoWorkList = new ArrayList<>();
                    //取出该托数据信息
                    List<FdTuoData> fdTuoDataList = fdTemplateData.getTuoInfos();
                    if(fdTuoDataList != null && fdTuoDataList.size() > 0){
                        for (int k = 0; k < fdTuoDataList.size(); k++) {
                            FdTuoData fdTuoData = fdTuoDataList.get(k);
                            //托词语
                            String word = fdTuoData.getWord();
                            //托次数
                            int times = fdTuoData.getTimes();
                            //循环托次数，将全部次数加起来存入临时列表
                            for (int t = 0; t < times; t++) {
                                tuoWorkList.add(word);
                            }
                        }
                    }


                    //托发言人信息的总数
                    int tuoWorkCount = tuoWorkList.size();
                    if(tuoWorkCount > 0){//托发言人数量大于0，才封装托信息
                        //循环子任务（群），每个群发送该商品
                        for (int j = 0; j < fdSendJobList_sub.size(); j++) {
                            //取出子任务
                            FdSendJob fdSendJob = fdSendJobList_sub.get(j);
                            //取出群
                            FdDevicePlanGroup fdDevicePlanGroup = fdDevicePlanGroupList.get(j);
                            //取出该子任务的消息列表
                            List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob.getEsFdGroupSendMsgList();

                            //取出该子任务的最后发送时间间隔
                            int sendMsgDelay = fdSendJob.getSendMsgDelay();
                            if(i == 0){ //第一次循环，需要加上群与群之间的消息间隔
                                sendMsgDelay = j * groupSendGap;
                            }else{//取出该任务的最后时间间隔+商品间隔时间
                                sendMsgDelay = sendMsgDelay + fdTemplate_gap;
                            }

                            //查询该子任务的配置的机器人数量
                            List<FdDevicePlanGroupTuo> fdDevicePlanGroupTuoList = fdDevicePlanGroupTuoMapper.findByListByFdDevicePlanGroupId(fdDevicePlanGroup.getId(), fdDevicePlanGroup.getMerId());
                            if(fdDevicePlanGroupTuoList != null && fdDevicePlanGroupTuoList.size() > 0){
                                //判断该群配置的发单托机器人数量和托发言消息数进行对比
                                int fdDevicePlangroupTuoCount = fdDevicePlanGroupTuoList.size();
                                //气氛组机器人数大于等于托发言人数
                                if(fdDevicePlangroupTuoCount >= tuoWorkCount){
                                    //取出气氛组机器人人数大于等于托发言人数时的发送配置参数
                                    Integer tuoGteContent = Tools.getInteger(fdDevicePlan.getTuoGteContent());
                                    //气氛组机器人随机发送,则随机打乱配置的机器人列表
                                    if(tuoGteContent == 0){
                                        Collections.shuffle(fdDevicePlanGroupTuoList);
                                    }
                                    //循环托发言数，依次建立消息
                                    for(int k=0; k<tuoWorkCount; k++){
                                        FdDevicePlanGroupTuo fdDevicePlanGroupTuo = fdDevicePlanGroupTuoList.get(k);
                                        //封装消息
                                        EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                                        esFdGroupSendMsg.setId(IdWorker.getIdStr());
                                        esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                                        esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                                        esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroupTuo.getTuoDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                                        if(device == null){
                                            continue;
                                        }
                                        esFdGroupSendMsg.setDeviceUniqueId(device.getId());
                                        esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                                        esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                                        esFdGroupSendMsg.setMsgType(MessageTypeEnum.MT_TEXT.getValue()); //托发文本消息
                                        esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                                        esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                                        //如果托发言人数超过1，则每次发言之后，消息延迟时间为1-5之间的随机数
                                        if(k>0){
                                            sendMsgDelay = sendMsgDelay + RandomUtil.getRandomInt(1, 5);
                                        }
                                        esFdGroupSendMsg.setDelay(sendMsgDelay);
                                        esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                                        esFdGroupSendMsg.setRetry(0);
                                        esFdGroupSendMsg.setVersion(0L);
                                        esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                                        esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                                        esFdGroupSendMsg.setNextIsTuo(2);//此消息为托
                                        esFdGroupSendMsg.setFrontMsgId(fdSendJob.getLastNoTuoMsgId());
                                        HashMap<String, String> msgHash = new HashMap<>();
                                        msgHash.put("content", tuoWorkList.get(k));
                                        esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                                        //添加到子任务中的临时发送消息列表中
                                        esFdGroupSendMsgList.add(esFdGroupSendMsg);
                                    }
                                }else{//气氛组机器人数小于托发言人数
                                    Integer tuoLtConteng = Tools.getInteger(fdDevicePlan.getTuoLtContent());
                                    if(tuoLtConteng == 0){//气氛组机器人重复发送
                                        //循环托发言数，依次建立消息
                                        for(int k=0; k<tuoWorkCount; k++){
                                            //对K针对机器人数进行取模，
                                            int k_index = k % fdDevicePlangroupTuoCount;
                                            FdDevicePlanGroupTuo fdDevicePlanGroupTuo = fdDevicePlanGroupTuoList.get(k_index);
                                            //封装消息
                                            EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                                            esFdGroupSendMsg.setId(IdWorker.getIdStr());
                                            esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                                            esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                                            esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                                            Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroupTuo.getTuoDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                                            if(device == null){
                                                continue;
                                            }
                                            esFdGroupSendMsg.setDeviceUniqueId(device.getId());
                                            esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                                            esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                                            esFdGroupSendMsg.setMsgType(MessageTypeEnum.MT_TEXT.getValue()); //托发文本消息
                                            esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                                            esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                                            //如果托发言人数超过1，则每次发言之后，消息延迟时间为1-5之间的随机数
                                            if(k>0){
                                                sendMsgDelay = sendMsgDelay + RandomUtil.getRandomInt(1, 5);
                                            }
                                            esFdGroupSendMsg.setDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setRetry(0);
                                            esFdGroupSendMsg.setVersion(0L);
                                            esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                                            esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                                            esFdGroupSendMsg.setNextIsTuo(2);//此消息为托
                                            esFdGroupSendMsg.setFrontMsgId(fdSendJob.getLastNoTuoMsgId());
                                            HashMap<String, String> msgHash = new HashMap<>();
                                            msgHash.put("content", tuoWorkList.get(k));
                                            esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                                            //添加到子任务中的临时发送消息列表中
                                            esFdGroupSendMsgList.add(esFdGroupSendMsg);
                                        }
                                    }else{//超过的内容数不发送
                                        //循环托配置的机器人数，依次建立消息,发言数多出的数量丢弃不发消息
                                        for(int k=0; k<fdDevicePlangroupTuoCount; k++){
                                            //对K针对机器人数进行取模，
                                            FdDevicePlanGroupTuo fdDevicePlanGroupTuo = fdDevicePlanGroupTuoList.get(k);
                                            //封装消息
                                            EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                                            esFdGroupSendMsg.setId(IdWorker.getIdStr());
                                            esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                                            esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                                            esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                                            Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroupTuo.getTuoDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                                            if(device == null){
                                                continue;
                                            }
                                            esFdGroupSendMsg.setDeviceUniqueId(device.getId());
                                            esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                                            esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                                            esFdGroupSendMsg.setMsgType(MessageTypeEnum.MT_TEXT.getValue()); //托发文本消息
                                            esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                                            esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                                            //如果托发言人数超过1，则每次发言之后，消息延迟时间为1-5之间的随机数
                                            if(k>0){
                                                sendMsgDelay = sendMsgDelay + RandomUtil.getRandomInt(1, 5);
                                            }
                                            esFdGroupSendMsg.setDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setRetry(0);
                                            esFdGroupSendMsg.setVersion(0L);
                                            esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                                            esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                                            esFdGroupSendMsg.setNextIsTuo(2);//此消息为托
                                            esFdGroupSendMsg.setFrontMsgId(fdSendJob.getLastNoTuoMsgId());
                                            HashMap<String, String> msgHash = new HashMap<>();
                                            msgHash.put("content", tuoWorkList.get(k));
                                            esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                                            //添加到子任务中的临时发送消息列表中
                                            esFdGroupSendMsgList.add(esFdGroupSendMsg);
                                        }
                                    }
                                }
                            }
                            //修改该任务新的最后发送时间间隔
                            fdSendJob.setSendMsgDelay(sendMsgDelay);
                        }
                    }
                }
            }
        }else{//顺序发送：一个任务中的全部内容在一个群中发送完成之后，在发下一个群
            //先循环子任务，在循环商品
            //每个任务的延时时间累加。默认从0开始
            int sendMsgDelay = 0;
            for (int i = 0; i < fdSendJobList_sub.size(); i++) {
                //取出子任务
                FdSendJob fdSendJob = fdSendJobList_sub.get(i);
                //取出群
                FdDevicePlanGroup fdDevicePlanGroup = fdDevicePlanGroupList.get(i);
                //取出该子任务的消息列表
                List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob.getEsFdGroupSendMsgList();
                //取出该子任务的最后发送时间间隔
                if(i != 0){ //不是第一次循环，则需要添加群与群之间的延迟时间间隔
                    sendMsgDelay = sendMsgDelay + groupSendGap;
                }
                for (int j = 0; j < fdTemplateDataList.size(); j++) {
                    //得到商品
                    FdTemplateData fdTemplateData = fdTemplateDataList.get(j);
                    //得到此商品的间隔时间
                    int fdTemplate_gap = Tools.getInteger(fdTemplateData.getGap());
                    //每个商品的发送时间=群内的开始时间+商品的间隔时间
                    sendMsgDelay = sendMsgDelay + fdTemplate_gap;
                    //判断该商品为否为托
                    if(Tools.getInteger(fdTemplateData.getMsgType()).intValue() != -1) {//不是托，则一个商品发送一次
                        //封装消息
                        EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                        esFdGroupSendMsg.setId(IdWorker.getIdStr());
                        //临时封装最后一条不是托信息的id
                        fdSendJob.setLastNoTuoMsgId(esFdGroupSendMsg.getId());
                        esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                        esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                        esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                        esFdGroupSendMsg.setDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                        if(device == null){
                            continue;
                        }
                        esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                        esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                        esFdGroupSendMsg.setMsgType(fdTemplateData.getMsgType());
                        esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                        esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                        esFdGroupSendMsg.setDelay(sendMsgDelay);
                        esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                        esFdGroupSendMsg.setRetry(0);
                        esFdGroupSendMsg.setVersion(0L);
                        esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                        esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                        //判断下个消息是否为托。
                        if( j+1 < fdTemplateDataList.size()){
                            FdTemplateData fdTemplateData_next = fdTemplateDataList.get(j+1);
                            if(fdTemplateData_next != null){
                                if(Tools.getInteger(fdTemplateData_next.getMsgType()).intValue() == -1) {//是托
                                    esFdGroupSendMsg.setNextIsTuo(1); //设置这个消息下一个消息是托
                                }
                            }
                        }
                        HashMap<String, String> msgHash = new HashMap<>();
                        if(fdTemplateData.getMsgType().intValue() == 0){ //文本消息
                            String content = fdTemplateData.getContent();
                            //替换商品变量
                            String content_new = contentTurnlink(content, fdDevicePlanGroup, fdDevicePlan, device);
                            msgHash.put("content", content_new);
                        }else if(fdTemplateData.getMsgType().intValue() == 1){
                            msgHash.put("imgUrl", fdTemplateData.getImgUrl());
                            msgHash.put("imgType", String.valueOf(fdTemplateData.getImgType()));
                        }else if(fdTemplateData.getMsgType().intValue() == 3){
                            msgHash.put("videoUrl", fdTemplateData.getVideoUrl());
                        }else if(fdTemplateData.getMsgType().intValue() == 5){
                            msgHash.put("cardTitle", fdTemplateData.getCardTitle());
                            msgHash.put("cardDes", fdTemplateData.getCardDes());
                            msgHash.put("cardImg", fdTemplateData.getCardImg());
                            msgHash.put("cardUrl", fdTemplateData.getCardUrl());
                        }else if(fdTemplateData.getMsgType().intValue() == 6){
                            msgHash.put("miniProAppId", fdTemplateData.getMiniProAppId());
                            msgHash.put("miniProTitle", fdTemplateData.getMiniProTitle());
                            msgHash.put("miniProDesc", fdTemplateData.getMiniProDesc());
                            msgHash.put("miniProUrl", fdTemplateData.getMiniProUrl());
                            msgHash.put("miniImgPwdStr", fdTemplateData.getMiniImgPwdStr());
                            msgHash.put("miniImgStr", fdTemplateData.getMiniImgStr());
                            msgHash.put("miniImgUrl", fdTemplateData.getMiniImgUrl());
                            msgHash.put("miniProGhId", fdTemplateData.getMiniProGhId());
                            msgHash.put("miniProName", fdTemplateData.getMiniProName());
                        }
                        esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                        //添加到子任务中的临时发送消息列表中
                        esFdGroupSendMsgList.add(esFdGroupSendMsg);
                    }else{//如果此商品是托
                        //临时存放托词语的列表
                        List<String> tuoWorkList = new ArrayList<>();
                        //取出该托数据信息
                        List<FdTuoData> fdTuoDataList = fdTemplateData.getTuoInfos();
                        if(fdTuoDataList != null && fdTuoDataList.size() > 0){
                            for (int k = 0; k < fdTuoDataList.size(); k++) {
                                FdTuoData fdTuoData = fdTuoDataList.get(k);
                                //托词语
                                String word = fdTuoData.getWord();
                                //托次数
                                int times = fdTuoData.getTimes();
                                //循环托次数，将全部次数加起来存入临时列表
                                for (int t = 0; t < times; t++) {
                                    tuoWorkList.add(word);
                                }
                            }
                        }

                        //托发言人信息的总数
                        int tuoWorkCount = tuoWorkList.size();
                        if(tuoWorkCount > 0) {//托发言人数量大于0，才封装托信息
                            //查询该子任务的配置的机器人数量
                            List<FdDevicePlanGroupTuo> fdDevicePlanGroupTuoList = fdDevicePlanGroupTuoMapper.findByListByFdDevicePlanGroupId(fdDevicePlanGroup.getId(), fdDevicePlanGroup.getMerId());
                            if(fdDevicePlanGroupTuoList != null && fdDevicePlanGroupTuoList.size() > 0){
                                //判断该群配置的发单托机器人数量和托发言消息数进行对比
                                int fdDevicePlangroupTuoCount = fdDevicePlanGroupTuoList.size();
                                //气氛组机器人数大于等于托发言人数
                                if(fdDevicePlangroupTuoCount >= tuoWorkCount){
                                    //取出气氛组机器人人数大于等于托发言人数时的发送配置参数
                                    Integer tuoGteContent = Tools.getInteger(fdDevicePlan.getTuoGteContent());
                                    //气氛组机器人随机发送,则随机打乱配置的机器人列表
                                    if(tuoGteContent == 0){
                                        Collections.shuffle(fdDevicePlanGroupTuoList);
                                    }
                                    //循环托发言数，依次建立消息
                                    for(int k=0; k<tuoWorkCount; k++){
                                        FdDevicePlanGroupTuo fdDevicePlanGroupTuo = fdDevicePlanGroupTuoList.get(k);
                                        //封装消息
                                        EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                                        esFdGroupSendMsg.setId(IdWorker.getIdStr());
                                        esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                                        esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                                        esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroupTuo.getTuoDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                                        if(device == null){
                                            continue;
                                        }
                                        esFdGroupSendMsg.setDeviceUniqueId(device.getId());
                                        esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                                        esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                                        esFdGroupSendMsg.setMsgType(MessageTypeEnum.MT_TEXT.getValue()); //托发文本消息
                                        esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                                        esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                                        //如果托发言人数超过1，则每次发言之后，消息延迟时间为1-5之间的随机数
                                        if(k>0){
                                            sendMsgDelay = sendMsgDelay + RandomUtil.getRandomInt(1, 5);
                                        }
                                        esFdGroupSendMsg.setDelay(sendMsgDelay);
                                        esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                                        esFdGroupSendMsg.setRetry(0);
                                        esFdGroupSendMsg.setVersion(0L);
                                        esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                                        esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                                        esFdGroupSendMsg.setNextIsTuo(2);//此消息为托
                                        esFdGroupSendMsg.setFrontMsgId(fdSendJob.getLastNoTuoMsgId());
                                        HashMap<String, String> msgHash = new HashMap<>();
                                        msgHash.put("content", tuoWorkList.get(k));
                                        esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                                        //添加到子任务中的临时发送消息列表中
                                        esFdGroupSendMsgList.add(esFdGroupSendMsg);
                                    }
                                }else{//气氛组机器人数小于托发言人数
                                    Integer tuoLtConteng = Tools.getInteger(fdDevicePlan.getTuoLtContent());
                                    if(tuoLtConteng == 0){//气氛组机器人重复发送
                                        //循环托发言数，依次建立消息
                                        for(int k=0; k<tuoWorkCount; k++){
                                            //对K针对机器人数进行取模，
                                            int k_index = k % fdDevicePlangroupTuoCount;
                                            FdDevicePlanGroupTuo fdDevicePlanGroupTuo = fdDevicePlanGroupTuoList.get(k_index);
                                            //封装消息
                                            EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                                            esFdGroupSendMsg.setId(IdWorker.getIdStr());
                                            esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                                            esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                                            esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                                            Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroupTuo.getTuoDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                                            if(device == null){
                                                continue;
                                            }
                                            esFdGroupSendMsg.setDeviceUniqueId(device.getId());
                                            esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                                            esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                                            esFdGroupSendMsg.setMsgType(MessageTypeEnum.MT_TEXT.getValue()); //托发文本消息
                                            esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                                            esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                                            //如果托发言人数超过1，则每次发言之后，消息延迟时间为1-5之间的随机数
                                            if(k>0){
                                                sendMsgDelay = sendMsgDelay + RandomUtil.getRandomInt(1, 5);
                                            }
                                            esFdGroupSendMsg.setDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setRetry(0);
                                            esFdGroupSendMsg.setVersion(0L);
                                            esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                                            esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                                            esFdGroupSendMsg.setNextIsTuo(2);//此消息为托
                                            esFdGroupSendMsg.setFrontMsgId(fdSendJob.getLastNoTuoMsgId());
                                            HashMap<String, String> msgHash = new HashMap<>();
                                            msgHash.put("content", tuoWorkList.get(k));
                                            esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                                            //添加到子任务中的临时发送消息列表中
                                            esFdGroupSendMsgList.add(esFdGroupSendMsg);
                                        }
                                    }else{//超过的内容数不发送
                                        //循环托配置的机器人数，依次建立消息,发言数多出的数量丢弃不发消息
                                        for(int k=0; k<fdDevicePlangroupTuoCount; k++){
                                            //对K针对机器人数进行取模，
                                            FdDevicePlanGroupTuo fdDevicePlanGroupTuo = fdDevicePlanGroupTuoList.get(k);
                                            //封装消息
                                            EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                                            esFdGroupSendMsg.setId(IdWorker.getIdStr());
                                            esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                                            esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                                            esFdGroupSendMsg.setMerId(fdSendJobDto.getMerId());
                                            Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroupTuo.getTuoDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdSendJobDto.getMerId());
                                            if(device == null){
                                                continue;
                                            }
                                            esFdGroupSendMsg.setDeviceUniqueId(device.getId());
                                            esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                                            esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                                            esFdGroupSendMsg.setMsgType(MessageTypeEnum.MT_TEXT.getValue()); //托发文本消息
                                            esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                                            esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                                            //如果托发言人数超过1，则每次发言之后，消息延迟时间为1-5之间的随机数
                                            if(k>0){
                                                sendMsgDelay = sendMsgDelay + RandomUtil.getRandomInt(1, 5);
                                            }
                                            esFdGroupSendMsg.setDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                                            esFdGroupSendMsg.setRetry(0);
                                            esFdGroupSendMsg.setVersion(0L);
                                            esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                                            esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                                            esFdGroupSendMsg.setNextIsTuo(2);//此消息为托
                                            esFdGroupSendMsg.setFrontMsgId(fdSendJob.getLastNoTuoMsgId());
                                            HashMap<String, String> msgHash = new HashMap<>();
                                            msgHash.put("content", tuoWorkList.get(k));
                                            esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                                            //添加到子任务中的临时发送消息列表中
                                            esFdGroupSendMsgList.add(esFdGroupSendMsg);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //修改该任务新的最后发送时间间隔
                fdSendJob.setSendMsgDelay(sendMsgDelay);
            }
        }

        //最后处理处理子任务和消息
        for (FdSendJob fdSendJob_sub : fdSendJobList_sub) {
            List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob_sub.getEsFdGroupSendMsgList();
            if(esFdGroupSendMsgList != null && esFdGroupSendMsgList.size() > 0){
                //添加任务
                fdSendJob_sub.setTotalCount(esFdGroupSendMsgList.size());
                fdSendJobMapper.insertSelective(fdSendJob_sub);
                //保存发送消息
                List<Map<String, Object>> list = BeanMapUtil.objectList2ListMap(esFdGroupSendMsgList);
                //存入ES
                //查询运营商其他索引分片
                String uzai_fd_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendJob_sub.getMerId());
                boolean result = elasticsearchUtilGroupMsg.addDataBatch(list, uzai_fd_group_send_msg);
                if(result){//保存成功，将子任务的id推送到MQ的延时队列当中
                    //fdSendMsgProducerService.pushFdSendJob(fdSendJob_sub.getId(), 0);
                    FdSendJobIdFeignDto fdSendJobIdFeignDto = new FdSendJobIdFeignDto();
                    fdSendJobIdFeignDto.setId(fdSendJob_sub.getId());
                    UzaiRespVo<Object> uzaiRespVo = uzaiBroadcastFeignService.fdPushChildid(fdSendJobIdFeignDto);
                    logger.info("--调用发单推送子任务id微服务接口-para={},result={}",JSONObject.toJSONString(fdSendJobIdFeignDto),JSONObject.toJSONString(uzaiRespVo));
                    if(uzaiRespVo == null || uzaiRespVo.getCode() != 200 ){//重复调用一次，防止第一次调用失败情况出现
                        UzaiRespVo<Object> uzaiRespVo_repeat = uzaiBroadcastFeignService.fdPushChildid(fdSendJobIdFeignDto);
                        logger.info("--调用发单推送子任务id微服务接口第一次失败，第二次调用-para={},result={}",JSONObject.toJSONString(fdSendJobIdFeignDto),JSONObject.toJSONString(uzaiRespVo_repeat));
                    }
                }else{//保存失败
                    fdSendJob_sub.setTotalCount(0);
                    fdSendJobMapper.updateTotalCountById(fdSendJob_sub);
                }
            }
        }
    }

    /**
     * 商品内容转链之后的字符串
     * @author jitwxs
     * @date 2022/12/21 9:46
     * @param content
     * @return null
     */
    public String contentTurnlink(String content, FdDevicePlanGroup fdDevicePlanGroup, FdDevicePlan fdDevicePlan, Device device){

        String content_new = Tools.getStr(content);

        if(StringUtils.isBlank(content)){
            return content_new;
        }

        //需要判断是否含有变量，如果含有变量，则需要判断该变量是否存在，存在，则转链
        //查询淘口令变量[淘口令+ID]
        String regex_pwd = FdGoodsParaEnum.PWD.getRegex();
        List<String> pwdList = Tools.findStrMatchListByRegex(content, regex_pwd);
        if(pwdList != null && pwdList.size() > 0){
            for (String pwdStr : pwdList) {
                //去除前后[]符号
                String pwdStr_new =  pwdStr.substring(1, pwdStr.length()-1);
                String[] goodsParaArr = pwdStr_new.split("\\+");
                String goodsParaId = goodsParaArr[1];
                FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdDevicePlanGroup.getMerId());
                if(fdGoodsPara != null){
                    //转链
                    SimpleTurnlinkVo goodInfo_pwd = getGoodInfo(fdGoodsPara, fdDevicePlanGroup, fdDevicePlan, device);
                    if(goodInfo_pwd != null && StringUtils.isNotBlank(goodInfo_pwd.getPurePwd())){
                        //淘口令
                        String pwd = goodInfo_pwd.getBuyPwd();
                        //淘口令前缀
                        String pwdpres = fdDevicePlan.getPwdpres();
                        //淘口令后缀
                        String pwdsufs = fdDevicePlan.getPwdsufs();
                        //如果前缀和后缀都有，则取裸淘口令
                        if(StringUtils.isNotBlank(pwdpres) && StringUtils.isNotBlank(pwdsufs)){
                            pwd = goodInfo_pwd.getPurePwd(); //裸淘口令
                            //根据设备方案配置的前缀和后缀拼凑淘口令
                            if(StringUtils.isNotBlank(pwdpres)){
                                List<String> pwdpreList = JSONObject.parseArray(pwdpres, String.class);
                                if(pwdpreList != null && pwdpreList.size() > 0){
                                    String pwdpre_random = pwdpreList.get((int) (Math.random() * pwdpreList.size()));
                                    pwd = pwdpre_random + pwd;
                                }
                            }
                            if(StringUtils.isNotBlank(pwdsufs)){
                                List<String> pwdsufList = JSONObject.parseArray(pwdsufs, String.class);
                                if(pwdsufList != null && pwdsufList.size() > 0){
                                    String pwdsuf_random = pwdsufList.get((int) (Math.random() * pwdsufList.size()));
                                    pwd = pwd + pwdsuf_random;
                                }
                            }
                        }
                        //替换淘口令
                        content_new = content.replace(pwdStr, pwd);
                    }
                }
            }
        }

        //查询短链接变量[短链接+ID]
        String regex_shortLink = FdGoodsParaEnum.SHORTLINK.getRegex();
        List<String> shortLinkList = Tools.findStrMatchListByRegex(content, regex_shortLink);
        if(shortLinkList != null && shortLinkList.size() > 0){
            for (String shortLinkStr : shortLinkList) {
                //去除前后[]符号
                String shortLinkStr_new =  shortLinkStr.substring(1, shortLinkStr.length()-1);
                String[] goodsParaArr = shortLinkStr_new.split("\\+");
                String goodsParaId = goodsParaArr[1];
                FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdDevicePlanGroup.getMerId());
                if(fdGoodsPara != null){
                    //转链
                    SimpleTurnlinkVo goodInfo_url = getGoodInfo(fdGoodsPara, fdDevicePlanGroup, fdDevicePlan, device);
                    if(goodInfo_url != null && StringUtils.isNotBlank(goodInfo_url.getBuyUrl())){
                        content_new = content.replace(shortLinkStr, goodInfo_url.getBuyUrl());
                    }
                }
            }
        }

        //查询抖音口令变量[抖音口令+ID]
        String regex_tiktokPwd = FdGoodsParaEnum.TIKTOK_PWD.getRegex();
        List<String> tiktokPwdList = Tools.findStrMatchListByRegex(content, regex_tiktokPwd);
        if(tiktokPwdList != null && tiktokPwdList.size() > 0){
            for (String tiktokPwdStr : tiktokPwdList) {
                //去除前后[]符号
                String tiktokPwdStr_new =  tiktokPwdStr.substring(1, tiktokPwdStr.length()-1);
                String[] goodsParaArr = tiktokPwdStr_new.split("\\+");
                String goodsParaId = goodsParaArr[1];
                FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdDevicePlanGroup.getMerId());
                if(fdGoodsPara != null){
                    //转链
                    SimpleTurnlinkVo goodInfo_pwd = getGoodInfo(fdGoodsPara, fdDevicePlanGroup, fdDevicePlan, device);
                    if(goodInfo_pwd != null && StringUtils.isNotBlank(goodInfo_pwd.getBuyPwd())){
                        content_new = content.replace(tiktokPwdStr, goodInfo_pwd.getBuyPwd());
                    }
                }
            }
        }

        return content_new;
    }

    /**
     * 获取商品信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param fdDevicePlanGroup
     * @return null
     */
    public SimpleTurnlinkVo getGoodInfo(FdGoodsPara fdGoodsPara, FdDevicePlanGroup fdDevicePlanGroup, FdDevicePlan fdDevicePlan, Device device){

        SimpleTurnlinkVo simpleTurnlinkVo = new SimpleTurnlinkVo();
        if(fdGoodsPara.getPlatform() == null){
            logger.info("请选择平台");
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择平台");
        }

        Long tbTokenId = null;
        String tbPid = "";
        String tbRid = "";
        Long jdTokenId = null;
        Long pddTokenId = null;
        Long vphTokenId = null;
        Long dyTokenId = null;
        Integer pddTokenType = null;
        Integer dyTokenType = null;
        //中间页参数
        Integer middlePageType = null;
        String middlePageUrl = "";
        //机器人身上的配置方案
        ConfigPlan configPlan = null;

        //淘宝商品
        if(fdGoodsPara.getPlatform().intValue() == 0){
            //1-从配置方案的群相关设置中获取联盟
            tbTokenId = fdDevicePlanGroup.getTbTokenId();
            tbPid = fdDevicePlanGroup.getTbPid();
            tbRid = fdDevicePlanGroup.getTbRid();
            middlePageType = fdDevicePlanGroup.getMiddlePageType();
            middlePageUrl = fdDevicePlanGroup.getMiddlePageUrl();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(tbTokenId == null){
                    //从配置方案中获取
                    tbTokenId = fdDevicePlan.getTbTokenId();
                }
                if(StringUtils.isBlank(tbPid)){
                    tbPid = fdDevicePlan.getTbPid();
                }
                if(StringUtils.isBlank(tbRid)){
                    tbRid = fdDevicePlan.getTbRid();
                }

                if(middlePageType == null){
                    middlePageType = fdDevicePlan.getMiddlePageType();
                }

                if(StringUtils.isBlank(middlePageUrl)){
                    middlePageUrl = fdDevicePlan.getMiddlePageUrl();
                }
            }

            //3-如果联盟信息或者中间页还为空，则从群管理配置的机器身上获取
            if(tbTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //淘宝商品不走机器人配置方案中获取，淘宝联盟转链需要用导购联盟
                    if(false) {
                        JSONObject jsonObject_tb = JSONObject.parseObject(configPlan.getTbAccountId());
                        if(jsonObject_tb != null) {
                            JSONArray jsonArray = jsonObject_tb.getJSONArray("tokens");
                            if (jsonArray != null && jsonArray.size() > 0) {
                                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                String tokenIds = jsonObject.getString("tokenIds");
                                List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                if (tokenList != null && tokenList.size() > 0) {
                                    tbTokenId = tokenList.get(0);
                                    TbToken tbToken = tbTokenMapper.selectById(tbTokenId, device.getMerId());
                                    if(tbToken != null){
                                        tbPid = tbToken.getDefPid();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //中间页还为空，则从群管理配置的机器人身上获取
            if(middlePageType == null || StringUtils.isBlank(middlePageUrl)){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //淘宝插件id
                    Long  tbId = configPlan.getTbId();
                    SysPlugin sysPlugin = sysPluginMapper.selectById(tbId, configPlan.getMerId());
                    if(sysPlugin != null){
                        //淘宝token
                        JSONObject jsonObject_tb = JSONObject.parseObject(sysPlugin.getData());
                        if(jsonObject_tb != null) {
                            middlePageType = jsonObject_tb.getInteger("middle_page_type");
                            middlePageUrl = jsonObject_tb.getString("middle_page_url");
                        }
                    }
                }
            }
        }else if(fdGoodsPara.getPlatform().intValue() == 1){//京东
            //1-从配置方案的群相关设置中获取联盟
            jdTokenId = fdDevicePlanGroup.getJdTokenId();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(jdTokenId == null){
                    //从配置方案中获取
                    jdTokenId = fdDevicePlan.getJdTokenId();
                }
            }

            //3-最后从配置的机器人当中获取
            if(jdTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //京东token
                    JSONObject jsonObject_jd = JSONObject.parseObject(configPlan.getJdAccountId());
                    if(jsonObject_jd != null) {
                        JSONArray jsonArray = jsonObject_jd.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                jdTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        }else if(fdGoodsPara.getPlatform().intValue() == 2){ //拼多多
            //1-从配置方案的群相关设置中获取联盟
            pddTokenType = fdDevicePlanGroup.getPddTokenType();
            if(pddTokenType != null && pddTokenType.intValue() == 1){ //推老板共享联盟
                pddTokenId = fdDevicePlanGroup.getPddTlbTokenId();
            }else{
                pddTokenId = fdDevicePlanGroup.getPddTokenId();
            }

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(pddTokenId == null){
                    //从配置方案中获取
                    pddTokenType = fdDevicePlan.getPddTokenType();
                    if(pddTokenType != null && pddTokenType.intValue() == 1){ //推老板共享联盟
                        pddTokenId = fdDevicePlan.getPddTlbTokenId();
                    }else{
                        pddTokenId = fdDevicePlan.getPddTokenId();
                    }
                }
            }

            //3-最后从机器人中的配置方案获取
            if(pddTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                if(configPlan != null){
                    //拼多多token
                    JSONObject jsonObject_pdd = null;
                    pddTokenType = configPlan.getPddAccountType();
                    if(pddTokenType != null && pddTokenType.intValue() == 1){ //推老板共享联盟
                        jsonObject_pdd = JSONObject.parseObject(configPlan.getTlbPddAccountId());
                    }else{ //拼多多联盟
                        jsonObject_pdd = JSONObject.parseObject(configPlan.getPddAccountId());
                    }
                    if(jsonObject_pdd != null) {
                        JSONArray jsonArray = jsonObject_pdd.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                pddTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        }else if(fdGoodsPara.getPlatform().intValue() == 3){ //唯品会
            //1-从配置方案的群相关设置中获取联盟
            vphTokenId = fdDevicePlanGroup.getVphTokenId();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(vphTokenId == null){
                    //从配置方案中获取
                    vphTokenId = fdDevicePlan.getVphTokenId();
                }
            }

            //3-最后从机器人中配置方案中获取
            if(vphTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //唯品会token
                    JSONObject jsonObject_vph = JSONObject.parseObject(configPlan.getVphAccountId());
                    if(jsonObject_vph != null) {
                        JSONArray jsonArray = jsonObject_vph.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                vphTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        }else if(fdGoodsPara.getPlatform().intValue() == 4){//抖音
            //1-从配置方案的群相关设置中获取联盟
            dyTokenType = fdDevicePlanGroup.getDyTokenType();
            if(dyTokenType != null && dyTokenType.intValue() == 1){
                dyTokenId = fdDevicePlanGroup.getDyTlbTokenId();
            }else{
                dyTokenId = fdDevicePlanGroup.getDyTokenId();
            }
            middlePageType = fdDevicePlanGroup.getMiddlePageType();
            middlePageUrl = fdDevicePlanGroup.getMiddlePageUrl();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(dyTokenId == null){
                    //从配置方案中获取
                    dyTokenType = fdDevicePlan.getDyTokenType();
                    if(dyTokenType != null && dyTokenType.intValue() == 1){
                        dyTokenId = fdDevicePlan.getDyTlbTokenId();
                    }else{
                        dyTokenId = fdDevicePlan.getDyTokenId();
                    }
                }
                if(middlePageType == null){
                    middlePageType = fdDevicePlan.getMiddlePageType();
                }

                if(StringUtils.isBlank(middlePageUrl)){
                    middlePageUrl = fdDevicePlan.getMiddlePageUrl();
                }
            }

            //3-最后从机器人中的配置方案获取
            if(dyTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //抖音token
                    JSONObject jsonObject_dy = null;
                    dyTokenType = configPlan.getDyAccountType();
                    if(dyTokenType != null && dyTokenType.intValue() == 1){ //抖音推老板共享联盟
                        jsonObject_dy = JSONObject.parseObject(configPlan.getTlbDyAccountId());
                    }else{ //拼多多联盟
                        jsonObject_dy = JSONObject.parseObject(configPlan.getDyAccountId());
                    }
                    if(jsonObject_dy != null) {
                        JSONArray jsonArray = jsonObject_dy.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                dyTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }

            //中间页还为空，则从群管理配置的机器人身上获取
            if(middlePageType == null || StringUtils.isBlank(middlePageUrl)){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //抖音插件id
                    Long dyId = configPlan.getDyId();
                    SysPlugin sysPlugin = sysPluginMapper.selectById(dyId, configPlan.getMerId());
                    if(sysPlugin != null){
                        //抖音token
                        JSONObject jsonObject_tb = JSONObject.parseObject(sysPlugin.getData());
                        if(jsonObject_tb != null) {
                            middlePageType = jsonObject_tb.getInteger("middle_page_type");
                            middlePageUrl = jsonObject_tb.getString("middle_page_url");
                        }
                    }
                }
            }
        }

        if(StringUtils.isBlank(fdGoodsPara.getItemId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品链接/id");
        }

        SimpleTurnLinkDto simpleTurnLinkDto = new  SimpleTurnLinkDto();
        simpleTurnLinkDto.setMerId(fdDevicePlanGroup.getMerId());
        simpleTurnLinkDto.setDeviceUniqueId(device.getId());
        simpleTurnLinkDto.setDeviceType(device.getRecvmsgType());
        simpleTurnLinkDto.setCouponId(fdGoodsPara.getCouponId());
        simpleTurnLinkDto.setChannel(OrderSourceEnum.WECHAT_FD.getId());//社群发单

        //淘宝和抖音平台还需要判断中间页
        if(fdGoodsPara.getPlatform().intValue() == 0 || fdGoodsPara.getPlatform().intValue() == 4) {
            //根据商品参数类型来做区分，如果是淘口令参数，则只需转链，如果是短链接参数，则还需转短链接
            if (Tools.getInteger(fdGoodsPara.getParaType()).intValue() == 1) { //短链接
                //该群内自定义配置、配置方案的配置、机器人身上配置，都没有找到中间页配置信息，故返回异常
                if (middlePageType == null) {

                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                            fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                            "",0L,
                            "社群群发-设备方案未配置中间页域名配置信息")));

                    //系统设置错误
                    AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                    alarmMsgFeignDto.setMerId(fdGoodsPara.getMerId());
                    alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                    alarmMsgFeignDto.setDeviceUniqueId(null);
                    alarmMsgFeignDto.setDeviceType(null);
                    //消息
                    JSONObject ext = new JSONObject();
                    ext.put("content", "社群群发-设备方案未配置中间页域名配置信息");
                    alarmMsgFeignDto.setExt(ext.toJSONString());
//                    UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                    logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                    //2024-01-09修改成直接发送MQ
                    noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
                }
                simpleTurnLinkDto.setGenerateShortUrl(1);
                if (middlePageType.intValue() == 0 || middlePageType.intValue() == 1) {//官方域名或自有域名
                    try {
                        simpleTurnLinkDto.setMiddlePageDomainId(Long.valueOf(middlePageUrl));
                    } catch (Exception e) {

                        logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                                fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                                "",0L,
                                "社群群发-设备方案配置的中间页域名信息有误")));

                        //系统设置错误
                        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                        alarmMsgFeignDto.setMerId(fdGoodsPara.getMerId());
                        alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                        alarmMsgFeignDto.setDeviceUniqueId(null);
                        alarmMsgFeignDto.setDeviceType(null);
                        //消息
                        JSONObject ext = new JSONObject();
                        ext.put("content", "社群群发-设备方案配置的中间页域名信息有误");
                        alarmMsgFeignDto.setExt(ext.toJSONString());
//                        UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                        logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                        //2024-01-09修改成直接发送MQ
                        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
                    }
                } else {//自定义链接
                    simpleTurnLinkDto.setMiddlePageUrl(middlePageUrl);
                }
            }
        }

        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = null;
        if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == fdGoodsPara.getPlatform().intValue()){ //淘宝

            if(tbTokenId == null){ //发单设备方案未配置淘宝联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置淘宝联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdGoodsPara.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置淘宝联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置淘宝联盟");
            }else{
                //判断输入得是商品id还是商品链接
                if(fdGoodsPara.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                }else{
                    //先查找淘宝id
                    String itemId = Tools.findTbItemIdByRegex(fdGoodsPara.getItemId());
                    if(StringUtils.isNotBlank(itemId)){
                        simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                    }else{
                        //查找淘口令，找到通过淘口令转链
                        String pwd = Tools.findTbPwdByRegex(fdGoodsPara.getItemId());
                        if(StringUtils.isNotBlank(pwd)){
                            simpleTurnLinkDto.setPwd(pwd);
                        }else{ //最后则默认为商品id
                            simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                        }
                    }
                }
                simpleTurnLinkDto.setTokenId(tbTokenId);
                simpleTurnLinkDto.setPid(tbPid);
                simpleTurnLinkDto.setRid(tbRid);
                uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用淘宝转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }


        }else if(PlatformTypeEnum.PT_JD.getId().intValue() == fdGoodsPara.getPlatform().intValue()){ //京东

            if(jdTokenId == null){ //发单设备方案未配置京东联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置京东联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdGoodsPara.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置京东联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置京东联盟");

            }else{
                //判断输入得是商品id还是商品链接
                if(fdGoodsPara.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                }else{
                    simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                }

                simpleTurnLinkDto.setTokenId(jdTokenId);
                uzaiRespVo = uzaiTurnlinkFeignService.jdTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用京东转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }else if(PlatformTypeEnum.PT_PDD.getId().intValue() == fdGoodsPara.getPlatform().intValue()){ //拼多多

            if(pddTokenId == null){ //发单设备方案未配置拼多多联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置拼多多联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdGoodsPara.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置拼多多联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置拼多多联盟");

            }else{

                //判断输入得是商品id还是商品链接
                if(fdGoodsPara.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                }else{
                    simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                }

                simpleTurnLinkDto.setTokenId(pddTokenId);
                simpleTurnLinkDto.setPddTokenType(pddTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.pddTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用拼多多转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }else if(PlatformTypeEnum.PT_VPH.getId().intValue() == fdGoodsPara.getPlatform().intValue()){ //唯品会
            if(vphTokenId == null){ //发单设备方案未配置唯品会联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置唯品会联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdGoodsPara.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置唯品会联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置唯品会联盟");

            }else{

                //判断输入得是商品id还是商品链接
                if(fdGoodsPara.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                }else{
                    simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                }

                simpleTurnLinkDto.setTokenId(vphTokenId);
                uzaiRespVo =uzaiTurnlinkFeignService.vphTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用唯品会转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(fdGoodsPara.getPlatform().intValue() == 4){ //抖音
            if(dyTokenId == null){ //发单设备方案未配置抖音联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置抖音联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdGoodsPara.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置抖音联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置抖音联盟");

            }else{
                //判断输入得是商品id还是商品链接
                simpleTurnLinkDto.setPwd(fdGoodsPara.getItemId());
                simpleTurnLinkDto.setTokenId(dyTokenId);
                simpleTurnLinkDto.setDyTokenType(dyTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.dyTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用抖音转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }

        if(uzaiRespVo != null){
            if(uzaiRespVo.getCode() == 200){
                simpleTurnlinkVo = uzaiRespVo.getData();
            }else{
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "转链失败；" + uzaiRespVo.getMsg())));

                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
            }
        }
        return simpleTurnlinkVo;
    }

    /**
     * 跟发发单任务
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param fdDevicePlanGroupList
     * @return null
     */
    //@Async("taskExecutor")
    @Override
    public void followFdSendJobTaskSync(List<FdTemplateData> fdTemplateDataList, FdDevicePlan fdDevicePlan, List<FdDevicePlanGroup> fdDevicePlanGroupList, List<FdSendJob> fdSendJobList_sub, FdFollowConfig fdFollowConfig){
        //群与群之间的发送时间间隔
        int groupSendGap = Tools.getInteger(fdDevicePlan.getGroupSendGap());
        //逐群发送：一个任务中同一个内容每个群都发送完成之后，在发送下一个内容
        if(Tools.getInteger(fdDevicePlan.getSendRule()).intValue() == 0) {
            //先循环该商品，然后在循环子任务
            for (int i = 0; i < fdTemplateDataList.size(); i++) {
                //得到商品
                FdTemplateData fdTemplateData = fdTemplateDataList.get(i);
                //得到此商品的间隔时间
                int fdTemplate_gap = Tools.getInteger(fdTemplateData.getGap());
                //循环子任务（群），每个群发送该商品
                for (int j = 0; j < fdSendJobList_sub.size(); j++) {
                    //取出子任务
                    FdSendJob fdSendJob = fdSendJobList_sub.get(j);
                    //取出群
                    FdDevicePlanGroup fdDevicePlanGroup = fdDevicePlanGroupList.get(j);
                    //取出该子任务的消息列表
                    List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob.getEsFdGroupSendMsgList();
                    //取出该子任务的最后发送时间间隔
                    int sendMsgDelay = fdSendJob.getSendMsgDelay();
                    if(i == 0){ //第一次循环，间隔时间为群与群之间的消息间隔 * 群数
                        sendMsgDelay = j * groupSendGap;
                    }else{//取出该任务的最后时间间隔+商品间隔时间
                        sendMsgDelay = sendMsgDelay + fdTemplate_gap;
                    }
                    //修改新的最后发送时间间隔
                    fdSendJob.setSendMsgDelay(sendMsgDelay);
                    //封装消息
                    EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                    esFdGroupSendMsg.setId(IdWorker.getIdStr());
                    //临时封装最后一条不是托信息的id
                    fdSendJob.setLastNoTuoMsgId(esFdGroupSendMsg.getId());
                    esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                    esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                    esFdGroupSendMsg.setMerId(fdDevicePlan.getMerId());
                    esFdGroupSendMsg.setDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdDevicePlan.getMerId());
                    if(device == null){
                        continue;
                    }
                    esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                    esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                    esFdGroupSendMsg.setMsgType(fdTemplateData.getMsgType());
                    esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                    esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                    esFdGroupSendMsg.setDelay(sendMsgDelay);
                    esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                    esFdGroupSendMsg.setRetry(0);
                    esFdGroupSendMsg.setVersion(0L);
                    esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                    esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                    HashMap<String, String> msgHash = new HashMap<>();
                    if(fdTemplateData.getMsgType().intValue() == 0){ //文本消息
                        String content = fdTemplateData.getContent();
                        //替换商品变量
                        String content_new = contentTurnlinkForFollow(content, fdDevicePlanGroup, fdDevicePlan, device, fdFollowConfig);
                        msgHash.put("content", content_new);
                    }else if(fdTemplateData.getMsgType().intValue() == 1 || fdTemplateData.getMsgType().intValue() == 4){ //图片信息
                        msgHash.put("imgUrl", fdTemplateData.getImgUrl());
                        msgHash.put("imgType", String.valueOf(fdTemplateData.getImgType()));
                    }else if(fdTemplateData.getMsgType().intValue() == 3){ //视频消息
                        msgHash.put("videoUrl", fdTemplateData.getVideoUrl());
                    }else if(fdTemplateData.getMsgType().intValue() == 5 || fdTemplateData.getMsgType().intValue() == 7){ //卡片消息
                        msgHash.put("cardTitle", fdTemplateData.getCardTitle());
                        msgHash.put("cardDes", fdTemplateData.getCardDes());
                        msgHash.put("cardImg", fdTemplateData.getCardImg());
                        //替换卡片url
                        String cardUrl = fdTemplateData.getCardUrl();
                        String cardUrl_new = contentTurnlinkForFollow(cardUrl, fdDevicePlanGroup, fdDevicePlan, device, fdFollowConfig);
                        msgHash.put("cardUrl", cardUrl_new);
                    }else if(fdTemplateData.getMsgType().intValue() == 6){ //小程序卡片
                        msgHash.put("miniProAppId", fdTemplateData.getMiniProAppId());
                        msgHash.put("miniProTitle", fdTemplateData.getMiniProTitle());
                        msgHash.put("miniProDesc", fdTemplateData.getMiniProDesc());
                        //替换小程序url
                        String miniProUrl = fdTemplateData.getMiniProUrl();
                        String miniProUrl_new = contentTurnlinkForFollow(miniProUrl, fdDevicePlanGroup, fdDevicePlan, device, fdFollowConfig);
                        msgHash.put("miniProUrl", miniProUrl_new);
                        msgHash.put("miniImgPwdStr", fdTemplateData.getMiniImgPwdStr());
                        msgHash.put("miniImgStr", fdTemplateData.getMiniImgStr());
                        msgHash.put("miniImgUrl", fdTemplateData.getMiniImgUrl());
                        msgHash.put("miniProGhId", fdTemplateData.getMiniProGhId());
                        msgHash.put("miniProName", fdTemplateData.getMiniProName());
                    }
                    esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                    //添加到子任务中的临时发送消息列表中
                    esFdGroupSendMsgList.add(esFdGroupSendMsg);

                    //临时将消息保持到子任务里
                    fdSendJob.setData(esFdGroupSendMsg.getMsg());
                }
            }
        }else{//顺序发送：一个任务中的全部内容在一个群中发送完成之后，在发下一个群
            //先循环子任务，在循环商品
            //每个任务的延时时间累加。默认从0开始
            int sendMsgDelay = 0;
            for (int i = 0; i < fdSendJobList_sub.size(); i++) {
                //取出子任务
                FdSendJob fdSendJob = fdSendJobList_sub.get(i);
                //取出群
                FdDevicePlanGroup fdDevicePlanGroup = fdDevicePlanGroupList.get(i);
                //取出该子任务的消息列表
                List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob.getEsFdGroupSendMsgList();
                //取出该子任务的最后发送时间间隔
                if(i != 0){ //不是第一次循环，则需要添加群与群之间的延迟时间间隔
                    sendMsgDelay = sendMsgDelay + groupSendGap;
                }
                for (int j = 0; j < fdTemplateDataList.size(); j++) {
                    //得到商品
                    FdTemplateData fdTemplateData = fdTemplateDataList.get(j);
                    //得到此商品的间隔时间
                    int fdTemplate_gap = Tools.getInteger(fdTemplateData.getGap());
                    //每个商品的发送时间=群内的开始时间+商品的间隔时间
                    sendMsgDelay = sendMsgDelay + fdTemplate_gap;
                    //封装消息
                    EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                    esFdGroupSendMsg.setId(IdWorker.getIdStr());
                    //临时封装最后一条不是托信息的id
                    fdSendJob.setLastNoTuoMsgId(esFdGroupSendMsg.getId());
                    esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                    esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                    esFdGroupSendMsg.setMerId(fdDevicePlan.getMerId());
                    esFdGroupSendMsg.setDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId());
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroup.getGroupSendDeviceUniqueId(), fdDevicePlanGroup.getDeviceType(), fdFollowConfig.getMerId());
                    if(device == null){
                        continue;
                    }
                    esFdGroupSendMsg.setDeviceId(device.getDeviceId());
                    esFdGroupSendMsg.setDeviceType(device.getRecvmsgType());
                    esFdGroupSendMsg.setMsgType(fdTemplateData.getMsgType());
                    esFdGroupSendMsg.setBizUserId(fdDevicePlanGroup.getWxid());
                    esFdGroupSendMsg.setNickName(fdDevicePlanGroup.getNick());
                    esFdGroupSendMsg.setDelay(sendMsgDelay);
                    esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                    esFdGroupSendMsg.setRetry(0);
                    esFdGroupSendMsg.setVersion(0L);
                    esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                    esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                    HashMap<String, String> msgHash = new HashMap<>();
                    if(fdTemplateData.getMsgType().intValue() == 0){ //文本消息
                        String content = fdTemplateData.getContent();
                        //替换商品变量
                        String content_new = contentTurnlinkForFollow(content, fdDevicePlanGroup, fdDevicePlan, device, fdFollowConfig);
                        msgHash.put("content", content_new);
                    }else if(fdTemplateData.getMsgType().intValue() == 1 || fdTemplateData.getMsgType().intValue() == 4){ //图片信息
                        msgHash.put("imgUrl", fdTemplateData.getImgUrl());
                        msgHash.put("imgType", String.valueOf(fdTemplateData.getImgType()));
                    }else if(fdTemplateData.getMsgType().intValue() == 3){ //视频消息
                        msgHash.put("videoUrl", fdTemplateData.getVideoUrl());
                    }else if(fdTemplateData.getMsgType().intValue() == 5 || fdTemplateData.getMsgType().intValue() == 7){ //卡片消息
                        msgHash.put("cardTitle", fdTemplateData.getCardTitle());
                        msgHash.put("cardDes", fdTemplateData.getCardDes());
                        msgHash.put("cardImg", fdTemplateData.getCardImg());
                        //替换卡片url
                        String cardUrl = fdTemplateData.getCardUrl();
                        String cardUrl_new = contentTurnlinkForFollow(cardUrl, fdDevicePlanGroup, fdDevicePlan, device, fdFollowConfig);
                        msgHash.put("cardUrl", cardUrl_new);
                    }else if(fdTemplateData.getMsgType().intValue() == 6){  //小程序卡片
                        msgHash.put("miniProAppId", fdTemplateData.getMiniProAppId());
                        msgHash.put("miniProTitle", fdTemplateData.getMiniProTitle());
                        msgHash.put("miniProDesc", fdTemplateData.getMiniProDesc());
                        //替换小程序url
                        String miniProUrl = fdTemplateData.getMiniProUrl();
                        String miniProUrl_new = contentTurnlinkForFollow(miniProUrl, fdDevicePlanGroup, fdDevicePlan, device, fdFollowConfig);
                        msgHash.put("miniProUrl", miniProUrl_new);
                        msgHash.put("miniImgPwdStr", fdTemplateData.getMiniImgPwdStr());
                        msgHash.put("miniImgStr", fdTemplateData.getMiniImgStr());
                        msgHash.put("miniImgUrl", fdTemplateData.getMiniImgUrl());
                        msgHash.put("miniProGhId", fdTemplateData.getMiniProGhId());
                        msgHash.put("miniProName", fdTemplateData.getMiniProName());
                    }
                    esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                    //添加到子任务中的临时发送消息列表中
                    esFdGroupSendMsgList.add(esFdGroupSendMsg);

                    //临时将消息保持到子任务里
                    fdSendJob.setData(esFdGroupSendMsg.getMsg());
                }
                //修改该任务新的最后发送时间间隔
                fdSendJob.setSendMsgDelay(sendMsgDelay);
            }
        }

        //最后处理处理子任务和消息
        for (FdSendJob fdSendJob_sub : fdSendJobList_sub) {
            List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob_sub.getEsFdGroupSendMsgList();
            if(esFdGroupSendMsgList != null && esFdGroupSendMsgList.size() > 0){
                //添加任务
                fdSendJob_sub.setTotalCount(esFdGroupSendMsgList.size());
                fdSendJob_sub.setFinishCount(esFdGroupSendMsgList.size());
                fdSendJobMapper.insertSelective(fdSendJob_sub);

//                //保存发送消息
//                List<Map<String, Object>> list = BeanMapUtil.objectList2ListMap(esFdGroupSendMsgList);
//                //存入ES
//                //查询运营商其他索引分片
//                String uzai_fd_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendJob_sub.getMerId());
//                boolean result = elasticsearchUtilGroupMsg.addDataBatch(list, uzai_fd_group_send_msg);
//                if(result){//保存成功，将子任务的id推送到MQ的延时队列当中
//                    //fdSendMsgProducerService.pushFdSendJob(fdSendJob_sub.getId(), 0);
//                    FdSendJobIdFeignDto fdSendJobIdFeignDto = new FdSendJobIdFeignDto();
//                    fdSendJobIdFeignDto.setId(fdSendJob_sub.getId());
//                    UzaiRespVo<Object> uzaiRespVo = uzaiBroadcastFeignService.fdPushChildid(fdSendJobIdFeignDto);
//                    logger.info("--调用发单推送子任务id微服务接口-para={},result={},list={}",JSONObject.toJSONString(fdSendJobIdFeignDto),JSONObject.toJSONString(uzaiRespVo), JSONObject.toJSONString(list));
//                    if(uzaiRespVo == null || uzaiRespVo.getCode() != 200 ){//重复调用一次，防止第一次调用失败情况出现
//                        UzaiRespVo<Object> uzaiRespVo_repeat = uzaiBroadcastFeignService.fdPushChildid(fdSendJobIdFeignDto);
//                        logger.info("--调用发单推送子任务id微服务接口第一次失败，第二次调用-para={},result={},list={}",JSONObject.toJSONString(fdSendJobIdFeignDto),JSONObject.toJSONString(uzaiRespVo_repeat), JSONObject.toJSONString(list));
//                    }
//                }else{//保存失败
//                    fdSendJob_sub.setTotalCount(0);
//                    fdSendJobMapper.updateTotalCountById(fdSendJob_sub);
//                }

                //直接调用MQ推送跟发消息,2024-01-09修改
                for (EsFdGroupSendMsg esFdGroupSendMsg : esFdGroupSendMsgList) {
                    //发送MQ消息
                    MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                    NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                    msgDto.setContent(noticeMsgDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(esFdGroupSendMsg.getDeviceType());
                    msgDto.setDeviceUniqueId(esFdGroupSendMsg.getDeviceUniqueId());
                    msgDto.setMerId(esFdGroupSendMsg.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());

                    //处理消息
                    String msgContent = esFdGroupSendMsg.getMsg();
                    JSONObject msgData = JSONObject.parseObject(msgContent);
                    int msgType = esFdGroupSendMsg.getMsgType();
                    Integer contentType = null;
                    String content = null;
                    switch (msgType){
                        case 0:
                            // 文本消息
                            contentType = MessageTypeEnum.MT_TEXT.getValue();
                            content = msgData.getString("content");
                            break;
                        case 1:
                            // 图片消息
                            contentType = MessageTypeEnum.MT_IMAGE.getValue();
                            content = msgData.getString("imgUrl");
                            break;
                        case 3:
                            // 视频
                            contentType = MessageTypeEnum.MT_VIDEO.getValue();
                            content = msgData.getString("videoUrl");
                            break;
                        case 5:
                            // 卡片消息
                            contentType = MessageTypeEnum.MT_URL_CARD.getValue();
                            // {"title":"","desc":"","imageUrl":"","url":"","appName":"","appId":"","appVersion":""}

                            Map<String,Object> cardMap = new HashMap<>();
                            cardMap.put("title",msgData.getString("cardTitle"));
                            cardMap.put("desc",msgData.getString("cardDes"));
                            cardMap.put("imageUrl",msgData.getString("cardImg"));
                            cardMap.put("url",msgData.getString("cardUrl"));
                            content = JSONObject.toJSONString(cardMap);
                            break;
                        case 6:
                            // 小程序
                            // {"title":"","desc":"","pagePath":"","imageUrl":"","imageKey":"","appId":"","sourceId":"","sourceName":""}
                            contentType = MessageTypeEnum.MT_WEAPP_CARD.getValue();
                            Map<String,Object> weAppMap = new HashMap<>();
                            weAppMap.put("title",msgData.getString("miniProTitle"));
                            weAppMap.put("desc",msgData.getString("miniProDesc"));
                            weAppMap.put("pagePath",msgData.getString("miniProUrl"));
                            weAppMap.put("imageUrl",msgData.getString("miniImgStr"));
                            weAppMap.put("imageKey",msgData.getString("miniImgPwdStr"));
                            weAppMap.put("appId",msgData.getString("miniProAppId"));
                            weAppMap.put("sourceId",msgData.getString("miniProGhId"));
                            weAppMap.put("sourceName",msgData.getString("miniProName"));
                            content = JSONObject.toJSONString(weAppMap);
                            break;
                    }

                    noticeMsgDto.setContent(content);
                    noticeMsgDto.setContentType(contentType);
                    noticeMsgDto.setBizUserId(esFdGroupSendMsg.getBizUserId());
                    noticeMsgDto.setGroupId(esFdGroupSendMsg.getBizUserId());
                    noticeMsgDto.setNickName(esFdGroupSendMsg.getNickName());
                    noticeMsgDto.setMsgSource(1);
                    noticeMsgDto.setDelay(esFdGroupSendMsg.getDelay());
                    noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                    noticeMsgPushProducerService.sendMessage(msgDto);
                }
            }
        }
    }




    /**
     * 跟发发单任务(气氛组)
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param fdTemplateDataList
     * @return null
     */
    //@Async("taskExecutor")
    @Override
    public void followQfFdSendJobTaskSync(List<FdTemplateData> fdTemplateDataList, List<FdSendJob> fdSendJobList_sub, FdFollowConfigQfGroup fdFollowConfigQfGroup, FdFollowConfigQfGroupTuo fdFollowConfigQfGroupTuo){

        //先循环子任务，在循环商品
        //每个任务的延时时间累加。默认从0开始
        int sendMsgDelay = 0;
        for (int i = 0; i < fdSendJobList_sub.size(); i++) {
            //取出子任务
            FdSendJob fdSendJob = fdSendJobList_sub.get(i);
            //取出该子任务的消息列表
            List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob.getEsFdGroupSendMsgList();
            //取出该子任务的最后发送时间间隔
            for (int j = 0; j < fdTemplateDataList.size(); j++) {
                //得到商品
                FdTemplateData fdTemplateData = fdTemplateDataList.get(j);
                //得到此商品的间隔时间
                int fdTemplate_gap = Tools.getInteger(fdTemplateData.getGap());
                //每个商品的发送时间=群内的开始时间+商品的间隔时间
                sendMsgDelay = sendMsgDelay + fdTemplate_gap;
                //封装消息
                EsFdGroupSendMsg esFdGroupSendMsg = new EsFdGroupSendMsg();
                esFdGroupSendMsg.setId(IdWorker.getIdStr());
                //临时封装最后一条不是托信息的id
                fdSendJob.setLastNoTuoMsgId(esFdGroupSendMsg.getId());
                esFdGroupSendMsg.setNextIsTuo(2);//自己是气氛组消息
                esFdGroupSendMsg.setFrontMsgId(null); //没有上一条消息
                esFdGroupSendMsg.setParentJobId(fdSendJob.getParentId());
                esFdGroupSendMsg.setChildJobId(fdSendJob.getId());
                esFdGroupSendMsg.setMerId(fdFollowConfigQfGroupTuo.getMerId());
                esFdGroupSendMsg.setDeviceUniqueId(fdFollowConfigQfGroupTuo.getTuoDeviceUniqueId());
                DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(fdFollowConfigQfGroup.getDeviceType());
                if(deviceTypeEnum == null ){
                    return;
                }
                esFdGroupSendMsg.setDeviceType(deviceTypeEnum.getId());
                esFdGroupSendMsg.setDeviceId(fdFollowConfigQfGroupTuo.getTuoDeviceId());
                esFdGroupSendMsg.setMsgType(fdTemplateData.getMsgType());
                esFdGroupSendMsg.setBizUserId(fdFollowConfigQfGroup.getGroupWxid());
                esFdGroupSendMsg.setNickName(fdFollowConfigQfGroup.getGroupUserName());
                esFdGroupSendMsg.setDelay(sendMsgDelay);
                esFdGroupSendMsg.setOriginalDelay(sendMsgDelay);
                esFdGroupSendMsg.setRetry(0);
                esFdGroupSendMsg.setVersion(0L);
                esFdGroupSendMsg.setCreateTime(fdSendJob.getCreateTime());
                esFdGroupSendMsg.setUpdateTime(fdSendJob.getUpdateTime());
                HashMap<String, String> msgHash = new HashMap<>();
                if(fdTemplateData.getMsgType().intValue() == 0){ //文本消息
                    String content = fdTemplateData.getContent();
                    msgHash.put("content", content);
                }else if(fdTemplateData.getMsgType().intValue() == 1){
                    msgHash.put("imgUrl", fdTemplateData.getImgUrl());
                    msgHash.put("imgType", String.valueOf(fdTemplateData.getImgType()));
                }else if(fdTemplateData.getMsgType().intValue() == 3){
                    msgHash.put("videoUrl", fdTemplateData.getVideoUrl());
                }
                esFdGroupSendMsg.setMsg(JSONObject.toJSONString(msgHash));
                //添加到子任务中的临时发送消息列表中
                esFdGroupSendMsgList.add(esFdGroupSendMsg);
            }
            //修改该任务新的最后发送时间间隔
            fdSendJob.setSendMsgDelay(sendMsgDelay);
        }

        //最后处理处理子任务和消息
        for (FdSendJob fdSendJob_sub : fdSendJobList_sub) {
            List<EsFdGroupSendMsg> esFdGroupSendMsgList = fdSendJob_sub.getEsFdGroupSendMsgList();
            if(esFdGroupSendMsgList != null && esFdGroupSendMsgList.size() > 0){
                //添加任务
                fdSendJob_sub.setTotalCount(esFdGroupSendMsgList.size());
                fdSendJobMapper.insertSelective(fdSendJob_sub);
                //保存发送消息
                List<Map<String, Object>> list = BeanMapUtil.objectList2ListMap(esFdGroupSendMsgList);
                //存入ES
                //查询运营商其他索引分片
                String uzai_fd_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.FD_GROUP_SEND_MSG, fdSendJob_sub.getMerId());
                boolean result = elasticsearchUtilGroupMsg.addDataBatch(list, uzai_fd_group_send_msg);
                if(result){//保存成功，将子任务的id推送到MQ的延时队列当中
                    //fdSendMsgProducerService.pushFdSendJob(fdSendJob_sub.getId(), 0);
                    FdSendJobIdFeignDto fdSendJobIdFeignDto = new FdSendJobIdFeignDto();
                    fdSendJobIdFeignDto.setId(fdSendJob_sub.getId());
                    UzaiRespVo<Object> uzaiRespVo = uzaiBroadcastFeignService.fdPushChildid(fdSendJobIdFeignDto);
                    logger.info("--调用发单推送子任务id微服务接口-para={},result={}",JSONObject.toJSONString(fdSendJobIdFeignDto),JSONObject.toJSONString(uzaiRespVo));
                    if(uzaiRespVo == null || uzaiRespVo.getCode() != 200 ){//重复调用一次，防止第一次调用失败情况出现
                        UzaiRespVo<Object> uzaiRespVo_repeat = uzaiBroadcastFeignService.fdPushChildid(fdSendJobIdFeignDto);
                        logger.info("--调用发单推送子任务id微服务接口第一次失败，第二次调用-para={},result={}",JSONObject.toJSONString(fdSendJobIdFeignDto),JSONObject.toJSONString(uzaiRespVo_repeat));
                    }
                }else{//保存失败
                    fdSendJob_sub.setTotalCount(0);
                    fdSendJobMapper.updateTotalCountById(fdSendJob_sub);
                }
            }
        }
    }

    /**
     * 商品内容转链之后的字符串(跟发)
     * @author jitwxs
     * @date 2022/12/21 9:46
     * @param content
     * @return null
     */
    public String contentTurnlinkForFollow(String content, FdDevicePlanGroup fdDevicePlanGroup, FdDevicePlan fdDevicePlan, Device device, FdFollowConfig fdFollowConfig){

        content = Tools.getStr(content);

        if(StringUtils.isBlank(content)){
            return content;
        }

        //判断是否替换淘口令和短链接
        if(Tools.getInteger(fdFollowConfig.getTurnlink()).intValue() == 1){ //--开启替换
            if(StringUtils.isNotBlank(content)){
                //短链接替换
                //先解析第三方工具商的短链接
                List<String> shortUrlList_old =  Tools.findHttpUrlListByRegex(content);
                if(shortUrlList_old != null && shortUrlList_old.size() > 0){
                    for (String shortUrl_old : shortUrlList_old) {
                        if(StringUtils.isNotBlank(shortUrl_old)){//不等于空，则调用解析第三方工具商短链接接口,获取商品平台信息
                            TextConvertGoodsDto textConvertGoodsDto = new TextConvertGoodsDto();
                            textConvertGoodsDto.setMerId(fdDevicePlan.getMerId());
                            textConvertGoodsDto.setText(shortUrl_old);
                            UzaiRespVo<ConvertGoodsDto> analyzeRes = clientApiService.convertGoods(textConvertGoodsDto);
                            if (analyzeRes.getCode() != 200) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                                        "",0L,
                                        "商品链接解析失败")));
                                continue;
                            }

                            ConvertGoodsDto data = analyzeRes.getData();
                            if (Objects.isNull(data)) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                                        "",0L,
                                        "商品链接解析失败")));
                                continue;
                            }

                            List<Integer> supportPlatform = Lists.newArrayList(PlatformTypeEnum.PT_TAOBAO_VALUE, PlatformTypeEnum.PT_JD_VALUE, PlatformTypeEnum.PT_VPH_VALUE, PlatformTypeEnum.PT_PDD_VALUE);
                            if (!supportPlatform.contains(data.getPlatform().getId())) {
                                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_FOLLOW_VALUE,
                                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                                        "",0L,
                                        "平台目前只支持淘宝、京东、拼多多、唯品会商品链接解析")));
                                continue;
                            }

                            //通过商品链接进行转链
                            SimpleTurnlinkVo content_simpleTurnlinkVo = getGoodInfo_Follow(null, null, shortUrl_old, null, fdDevicePlanGroup, fdDevicePlan, device, 1, data.getPlatform().getId());
                            if(content_simpleTurnlinkVo != null){
                                //新的短链接
                                String content_buyUrl_new = Tools.getStr(content_simpleTurnlinkVo.getBuyUrl());
                                if(StringUtils.isBlank(content_buyUrl_new)){//转链内容为空时需要根据任务中配置的字段进行判断
                                    if(Tools.getInteger(fdFollowConfig.getTurnlinkDeal()).intValue() == 0){ //替换为空
                                        //先替换有https开头的
                                        content = content.replace(shortUrl_old, content_buyUrl_new);
                                        //先替换没有https开头的
                                        String shortUrl_old_noHttps = shortUrl_old.replace("https://","");
                                        content = content.replace(shortUrl_old_noHttps, content_buyUrl_new);
                                    }
                                }else{
                                    //先替换有https开头的
                                    content = content.replace(shortUrl_old, content_buyUrl_new);
                                    //先替换没有https开头的
                                    String shortUrl_old_noHttps = shortUrl_old.replace("https://","");
                                    content = content.replace(shortUrl_old_noHttps, content_buyUrl_new);
                                }
                            }
                        }
                    }
                }

                //淘口令替换
                List<String> content_purePwdList_old =  Tools.findTbPwdListByRegex(content);
                if(content_purePwdList_old != null && content_purePwdList_old.size() > 0){
                    for (String content_purePwd_old : content_purePwdList_old) {
                        if(StringUtils.isNotBlank(content_purePwd_old)){
                            SimpleTurnlinkVo content_simpleTurnlinkVo = getGoodInfo_Follow(null, content_purePwd_old,null, null, fdDevicePlanGroup, fdDevicePlan, device, 0, PlatformTypeEnum.PT_TAOBAO_VALUE);
                            if(content_simpleTurnlinkVo != null){
                                //新的淘口令
                                String content_purePwd_new = Tools.getStr(content_simpleTurnlinkVo.getPurePwd());
                                if(StringUtils.isBlank(content_purePwd_new)){//转链内容为空时需要根据任务中配置的字段进行判断
                                    if(Tools.getInteger(fdFollowConfig.getTurnlinkDeal()).intValue() == 0) { //替换为空
                                        content = content.replace(content_purePwd_old, content_purePwd_new);
                                    }
                                }else{
                                    content = content.replace(content_purePwd_old, content_purePwd_new);
                                }
                            }
                        }
                    }
                }
            }
        }

        return content;
    }


    /**
     * 解析第三方工具商的短链接
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param  url
     * @param  device
     */
    private TbPartnerurlAnalysisVo tbPartnerurlAnalysis_follow(String url, Device device){
        TbPartnerurlAnalysisVo tbPartnerurlAnalysisVo = new TbPartnerurlAnalysisVo();

        if(StringUtils.isBlank(url)){
            return tbPartnerurlAnalysisVo;
        }

        if(device == null){
            return tbPartnerurlAnalysisVo;
        }

        //调用获取淘口令微服务接口
        TbPartnerurlAnalysisDto tbPartnerurlAnalysisDto = new TbPartnerurlAnalysisDto();
        tbPartnerurlAnalysisDto.setMerId(device.getMerId());
        tbPartnerurlAnalysisDto.setDeviceId(device.getDeviceId());
        tbPartnerurlAnalysisDto.setDeviceType(device.getRecvmsgType());
        tbPartnerurlAnalysisDto.setDeviceUniqueId(device.getId());
        tbPartnerurlAnalysisDto.setUrl(url);
        tbPartnerurlAnalysisDto.setReqId(String.valueOf(IdWorker.getId()));
        UzaiRespVo<TbPartnerurlAnalysisVo> uzaiRespVo = uzaiTurnlinkFeignService.tbPartnerurlAnalysis(tbPartnerurlAnalysisDto);
        logger.info("--调用解析第三方工具商的短链接微服务接口--,para={}, result={}", JSONObject.toJSONString(tbPartnerurlAnalysisDto), JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            return uzaiRespVo.getData();
        }
        return tbPartnerurlAnalysisVo;
    }


    /**
     * 转链生成新的淘口令
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param  pwd
     * @para bizSceneId:务场景ID 非必填，解析淘口令得接口返回了就带过来，没返回就不带
     * @param  device
     */
    private SimpleTurnlinkVo getGoodInfo_Follow(String itemId, String pwd, String url,String bizSceneId, FdDevicePlanGroup fdDevicePlanGroup, FdDevicePlan fdDevicePlan, Device device, int generateShortUrl, Integer platform){

        platform = Tools.getInteger(platform);

        SimpleTurnlinkVo simpleTurnlinkVo = new SimpleTurnlinkVo();

        Long tbTokenId = null;
        String tbPid = "";
        String tbRid = "";
        Long jdTokenId = null;
        Long pddTokenId = null;
        Long vphTokenId = null;
        Long dyTokenId = null;
        Integer pddTokenType = null;
        Integer dyTokenType = null;

        //中间页参数
        Integer middlePageType = null;
        String middlePageUrl = "";
        //机器人身上的配置方案
        ConfigPlan configPlan = null;


        //淘宝商品
        if(platform.intValue() == PlatformTypeEnum.PT_TAOBAO_VALUE){
            //1-从配置方案的群相关设置中获取联盟
            tbTokenId = fdDevicePlanGroup.getTbTokenId();
            tbPid = fdDevicePlanGroup.getTbPid();
            tbRid = fdDevicePlanGroup.getTbRid();
            middlePageType = fdDevicePlanGroup.getMiddlePageType();
            middlePageUrl = fdDevicePlanGroup.getMiddlePageUrl();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(tbTokenId == null){
                    //从配置方案中获取
                    tbTokenId = fdDevicePlan.getTbTokenId();
                }
                if(StringUtils.isBlank(tbPid)){
                    tbPid = fdDevicePlan.getTbPid();
                }
                if(StringUtils.isBlank(tbRid)){
                    tbRid = fdDevicePlan.getTbRid();
                }

                if(middlePageType == null){
                    middlePageType = fdDevicePlan.getMiddlePageType();
                }

                if(StringUtils.isBlank(middlePageUrl)){
                    middlePageUrl = fdDevicePlan.getMiddlePageUrl();
                }
            }

            //3-如果联盟信息或者中间页还为空，则从群管理配置的机器身上获取
            if(tbTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //淘宝token不从配置方案的机器人上获取联盟，淘宝商品采用导购联盟进行转链
                    if(false){
                        JSONObject jsonObject_tb = JSONObject.parseObject(configPlan.getTbAccountId());
                        if(jsonObject_tb != null) {
                            JSONArray jsonArray = jsonObject_tb.getJSONArray("tokens");
                            if (jsonArray != null && jsonArray.size() > 0) {
                                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                String tokenIds = jsonObject.getString("tokenIds");
                                List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                if (tokenList != null && tokenList.size() > 0) {
                                    tbTokenId = tokenList.get(0);
                                    TbToken tbToken = tbTokenMapper.selectById(tbTokenId, device.getMerId());
                                    if(tbToken != null){
                                        tbPid = tbToken.getDefPid();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //中间页还为空，则从群管理配置的机器人身上获取
            if(middlePageType == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //淘宝插件id
                    Long  tbId = configPlan.getTbId();
                    SysPlugin sysPlugin = sysPluginMapper.selectById(tbId, configPlan.getMerId());
                    if(sysPlugin != null){
                        //淘宝token
                        JSONObject jsonObject_tb = JSONObject.parseObject(sysPlugin.getData());
                        if(jsonObject_tb != null) {
                            middlePageType = jsonObject_tb.getInteger("middle_page_type");
                            middlePageUrl = jsonObject_tb.getString("middle_page_url");
                        }
                    }
                }
            }
        }else if(platform.intValue() == PlatformTypeEnum.PT_JD_VALUE){//京东
            //1-从配置方案的群相关设置中获取联盟
            jdTokenId = fdDevicePlanGroup.getJdTokenId();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(jdTokenId == null){
                    //从配置方案中获取
                    jdTokenId = fdDevicePlan.getJdTokenId();
                }
            }

            //3-最后从配置的机器人当中获取
            if(jdTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //京东token
                    JSONObject jsonObject_jd = JSONObject.parseObject(configPlan.getJdAccountId());
                    if(jsonObject_jd != null) {
                        JSONArray jsonArray = jsonObject_jd.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                jdTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        }else if(platform.intValue() == PlatformTypeEnum.PT_PDD_VALUE){ //拼多多
            //1-从配置方案的群相关设置中获取联盟
            pddTokenType = fdDevicePlanGroup.getPddTokenType();
            if(pddTokenType != null && pddTokenType.intValue() == 1){
                pddTokenId = fdDevicePlanGroup.getPddTlbTokenId();
            }else{
                pddTokenId = fdDevicePlanGroup.getPddTokenId();
            }

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(pddTokenId == null){
                    pddTokenType = fdDevicePlan.getPddTokenType();
                    if(pddTokenType != null && pddTokenType.intValue() == 1){
                        pddTokenId = fdDevicePlan.getPddTlbTokenId();
                    }else{
                        pddTokenId = fdDevicePlan.getPddTokenId();
                    }
                }
            }

            //3-最后从机器人中的配置方案获取
            if(pddTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                if(configPlan != null){
                    //拼多多token
                    JSONObject jsonObject_pdd = null;
                    pddTokenType = configPlan.getPddAccountType();
                    if(pddTokenType != null && pddTokenType.intValue() == 1){ //推老板共享联盟
                        jsonObject_pdd = JSONObject.parseObject(configPlan.getTlbPddAccountId());
                    }else{ //拼多多联盟
                        jsonObject_pdd = JSONObject.parseObject(configPlan.getPddAccountId());
                    }
                    if(jsonObject_pdd != null) {
                        JSONArray jsonArray = jsonObject_pdd.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                pddTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        }else if(platform.intValue() == PlatformTypeEnum.PT_VPH_VALUE){ //唯品会
            //1-从配置方案的群相关设置中获取联盟
            vphTokenId = fdDevicePlanGroup.getVphTokenId();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(vphTokenId == null){
                    //从配置方案中获取
                    vphTokenId = fdDevicePlan.getVphTokenId();
                }
            }

            //3-最后从机器人中配置方案中获取
            if(vphTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //唯品会token
                    JSONObject jsonObject_vph = JSONObject.parseObject(configPlan.getVphAccountId());
                    if(jsonObject_vph != null) {
                        JSONArray jsonArray = jsonObject_vph.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                vphTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        }else if(platform.intValue() == PlatformTypeEnum.PT_DY_VALUE){ //抖音
            //1-从配置方案的群相关设置中获取联盟
            dyTokenType = fdDevicePlanGroup.getDyTokenType();
            if(dyTokenType != null && dyTokenType.intValue() == 1){
                dyTokenId = fdDevicePlanGroup.getDyTlbTokenId();
            }else{
                dyTokenId = fdDevicePlanGroup.getDyTokenId();
            }

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if(fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if(dyTokenId == null){
                    //从配置方案中获取
                    dyTokenType = fdDevicePlan.getDyTokenType();
                    if(dyTokenType != null && dyTokenType.intValue() == 1){
                        dyTokenId = fdDevicePlan.getDyTlbTokenId();
                    }else{
                        dyTokenId = fdDevicePlan.getDyTokenId();
                    }
                }
                if(middlePageType == null){
                    middlePageType = fdDevicePlan.getMiddlePageType();
                }
                if(StringUtils.isBlank(middlePageUrl)){
                    middlePageUrl = fdDevicePlan.getMiddlePageUrl();
                }
            }

            //3-最后从机器人中的配置方案获取
            if(dyTokenId == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //抖音token
                    JSONObject jsonObject_dy = null;
                    dyTokenType = configPlan.getDyAccountType();
                    if(dyTokenType != null && dyTokenType.intValue() == 1){ //抖音推老板共享联盟
                        jsonObject_dy = JSONObject.parseObject(configPlan.getTlbDyAccountId());
                    }else{ //拼多多联盟
                        jsonObject_dy = JSONObject.parseObject(configPlan.getDyAccountId());
                    }
                    if(jsonObject_dy != null) {
                        JSONArray jsonArray = jsonObject_dy.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                dyTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }

            //中间页还为空，则从群管理配置的机器人身上获取
            if(middlePageType == null){
                if(configPlan == null){
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if(configPlan != null){
                    //抖音插件id
                    Long dyId = configPlan.getDyId();
                    SysPlugin sysPlugin = sysPluginMapper.selectById(dyId, configPlan.getMerId());
                    if(sysPlugin != null){
                        //淘宝token
                        JSONObject jsonObject_tb = JSONObject.parseObject(sysPlugin.getData());
                        if(jsonObject_tb != null) {
                            middlePageType = jsonObject_tb.getInteger("middle_page_type");
                            middlePageUrl = jsonObject_tb.getString("middle_page_url");
                        }
                    }
                }
            }
        }

        SimpleTurnLinkDto simpleTurnLinkDto = new  SimpleTurnLinkDto();
        //判断输入得是商品id还是商品链接
        simpleTurnLinkDto.setItemId(itemId);
        simpleTurnLinkDto.setPwd(pwd);
        simpleTurnLinkDto.setUrl(url);
        simpleTurnLinkDto.setMerId(fdDevicePlanGroup.getMerId());
        simpleTurnLinkDto.setCouponId("");
        simpleTurnLinkDto.setBizSceneId(bizSceneId);
        simpleTurnLinkDto.setChannel(OrderSourceEnum.WECHAT_FD.getId());//社群发单

        //根据商品参数类型来做区分，如果是淘口令参数，则只需转链，如果是短链接参数，则还需转短链接
        if(platform.intValue() == PlatformTypeEnum.PT_TAOBAO_VALUE || platform.intValue() == PlatformTypeEnum.PT_DY_VALUE){//只有淘宝和抖音 才有中间页
            if(generateShortUrl == 1){ //短链接
                //该群内自定义配置、配置方案的配置、机器人身上配置，都没有找到中间页配置信息，故返回异常
                if(middlePageType == null){
                    logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                            fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                            "",0L,
                            "系统未找到中间页配置信息")));
                    simpleTurnLinkDto.setGenerateShortUrl(0);
                }else{
                    simpleTurnLinkDto.setGenerateShortUrl(1);
                    if(middlePageType.intValue() == 0 || middlePageType.intValue() == 1){//官方域名或自有域名
                        simpleTurnLinkDto.setMiddlePageDomainId(Long.valueOf(middlePageUrl));
                    }else{//自定义链接
                        simpleTurnLinkDto.setMiddlePageUrl(middlePageUrl);
                    }
                }
            }
        }

        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = null;
        if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == platform.intValue()){ //淘宝

            if(tbTokenId == null){ //发单设备方案未配置淘宝联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置淘宝联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdDevicePlan.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置淘宝联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
            }else{
                simpleTurnLinkDto.setTokenId(tbTokenId);
                simpleTurnLinkDto.setPid(tbPid);
                simpleTurnLinkDto.setRid(tbRid);
                uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用淘宝转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }else if(PlatformTypeEnum.PT_JD.getId().intValue() == platform.intValue()){ //京东

            if(jdTokenId == null){ //发单设备方案未配置京东联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置京东联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdDevicePlan.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置京东联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
            }else{
                simpleTurnLinkDto.setTokenId(jdTokenId);
                uzaiRespVo = uzaiTurnlinkFeignService.jdTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用京东转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }else if(PlatformTypeEnum.PT_PDD.getId().intValue() == platform.intValue()){ //拼多多

            if(pddTokenId == null){ //发单设备方案未配置拼多多联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置拼多多联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdDevicePlan.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置拼多多联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

            }else{
                simpleTurnLinkDto.setTokenId(pddTokenId);
                simpleTurnLinkDto.setPddTokenType(pddTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.pddTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用拼多多转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }else if(PlatformTypeEnum.PT_VPH.getId().intValue() == platform.intValue()){ //唯品会

            if(vphTokenId == null){ //发单设备方案未配置拼多多联盟id

                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_FOLLOW_VALUE,
                        fdDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "社群群发-设备方案未配置唯品会联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(fdDevicePlan.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "社群群发-设备方案未配置唯品会联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));
                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
            }else{
                simpleTurnLinkDto.setTokenId(vphTokenId);
                uzaiRespVo =uzaiTurnlinkFeignService.vphTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用唯品会转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }

        }

        logger.info("---自动跟发转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));

        if(uzaiRespVo != null){
            if(uzaiRespVo.getCode() == 200){
                simpleTurnlinkVo = uzaiRespVo.getData();
            }else{
                logger.error("----获取商品信息失败----result={}", JSONObject.toJSONString(uzaiRespVo));
            }
        }

        return simpleTurnlinkVo;
    }

}
